<?php
namespace Components\User\Sha\Mutually\Sell;

use Components\User\Sha\Auth;
use Components\User\Sha\Wallet\Constants as WalletConstants;
use Components\User\Sha\Service as UserService;
use Components\User\Sha\Wallet\Service as UserWalletService;
use Components\User\Sha\Validation as UserValidation;

class Facade {
	public function updateStatusByToken($token, $id, $status, $data) {
		$checkToken = Auth::checkToken($token);
		if($checkToken['code'] != 0) { return $checkToken; }

		$resUser = (new UserService()) -> findFirst(['conditions'=>'id = '.$checkToken['payload']['user']['id']]);
		if($resUser['code'] != 0) { return $resUser; }
		$checkSafePassword = (new UserValidation()) -> checkSafePassword($data['safe_password'], $resUser['model'] -> safe_password);
		if($checkSafePassword['code'] != 0) { return ['code'=>$checkSafePassword['code'],'msg'=>'安全密码错误']; }

		return (new Logic()) -> updateStatus($id, $status, $data);
	}

  public function findFirstByIdAndToken($id, $token) {
    $checkToken = Auth::checkToken($token);
    if($checkToken['code'] != 0) { return $checkToken; }

    return (new Logic()) -> findFirstById($id);
  }

  protected function pagerQuery($query) {
    if(!isset($query['page'])) {
      $query['page'] = 1;
    } else if($query['page'] <= 0)  {
      $query['page'] = 1;
    } else {
      $query['page'] = abs($query['page']);
    }

    if(!isset($query['limit'])) {
      $query['limit'] = 10;
    } else if($query['limit'] <= 0)  {
      $query['limit'] = 10;
    } else {
      $query['limit'] = abs($query['limit']);
    }

    return $query;
  }

  public function pagerByToken($token, $query) {
    $checkToken = Auth::checkToken($token);
    if($checkToken['code'] != 0) { return $checkToken; }

    $query = $this -> pagerQuery($query);
    $parameters['conditions']['user'] = ['id' => $checkToken['payload']['user']['id']];
    return (new Logic()) -> pagerUseParameters($query['limit'], $query['page'], $parameters);
  }

  public function pager($query) {
    $query = $this -> pagerQuery($query);
    return (new Logic()) -> pager($query['limit'], $query['page']);
  }
  
  public function createByToken($token, $data) {
    $checkToken = Auth::checkToken($token);
    if($checkToken['code'] != 0) { return $checkToken; }

    if($data['amount'] <= 0) { return ['code'=>-1,'msg'=>'数量不能少于0']; }
    if($data['amount'] % 1000 != 0) { return ['code'=>-1,'msg'=>'请输入1000倍的整数']; }

    $field = WalletConstants::getByIndex('user_wallet_record_fields', $data['field']);
    if(!$field) { return ['code'=>-1,'msg'=>'字段不存在或已删除']; }

    $resUser = (new UserService()) -> findFirst(['conditions'=>'id = '.$checkToken['payload']['user']['id']]);
    if($resUser['code'] != 0) { return $resUser; }

    $checkSafePassword = (new UserValidation()) -> checkSafePassword($data['safe_password'], $resUser['model'] -> safe_password);
    if($checkSafePassword['code'] != 0) { return ['code'=>$checkSafePassword['code'],'msg'=>'安全密码错误']; }

    $userWallet = (new UserWalletService()) -> findFirstById($resUser['model'] -> id);
    if($userWallet['code'] != 0) { return $userWallet; }

    if($userWallet['model'] -> $field < $data['amount']) { return ['code'=>-1,'msg'=>'余额不足']; }

    if($userWallet['model'] -> appointment < 1) { return ['code'=>-1,'msg'=>'预约币不足']; }

    $lastMutuallySellModel = Model::findFirst([
      'conditions' => 'user_id = ' . $resUser['model'] -> id . ' AND field = ' . $data['field'],
      'order' => 'id DESC'
    ]);
    if(
      $lastMutuallySellModel &&
      $lastMutuallySellModel -> status != 80 &&
      $lastMutuallySellModel -> status != 90
    ) { return ['code'=>-1,'msg'=>'请等候上一单匹配完成']; }

    $currentTime = time();
    $fieldModelName = WalletConstants::getByIndex('user_wallet_record_fields_model_name', $data['field']);
    $fieldModelClass = '\\Components\\User\\Sha\\Wallet\\Record\\'.$fieldModelName.'Model';
    $userWalletRecord = new $fieldModelClass([
      'user_id' => $resUser['model'] -> id,
      'type' => 12101,
      'action' => 45,
      'amount' => $data['amount'],
      'amount_old' => $userWallet['model'] -> $field,
      'create_time' => $currentTime,
      'remark' => '提现'
    ]);

    $userWalletAppointmentRecord = new \Components\User\Sha\Wallet\Record\AppointmentModel([
      'user_id' => $resUser['model'] -> id,
      'type' => 17101,
      'action' => 45,
      'amount' => 1,
      'amount_old' => $userWallet['model'] -> appointment,
      'create_time' => $currentTime,
      'remark' => '使用'
    ]);

    $mutuallySellModel = new Model([
      'user_id' => $resUser['model'] -> id,
      'field' => $data['field'],
      'amount' => $data['amount'],
      'original_amount' => $data['amount'],
      'average' => 0,
      'create_time' => $currentTime,
      'status' => 10
    ]);

    $transaction = (new \Phalcon\Mvc\Model\Transaction\Manager()) -> get();

    try {
      $userWallet['model'] -> $field -= $data['amount'];
      $userWallet['model'] -> appointment -= 1;
      $userWallet['model'] -> setTransaction($transaction);
      if(!$userWallet['model'] -> update()) {
        $msgs = $userWallet['model'] -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }

      $mutuallySellModel -> setTransaction($transaction);
      if(!$mutuallySellModel -> create()) {
        $msgs = $mutuallySellModel -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }

      $userWalletRecord -> amount_new = $userWallet['model'] -> $field;
      $userWalletRecord -> setTransaction($transaction);
      if(!$userWalletRecord -> create()) {
        $msgs = $userWalletRecord['model'] -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }

      $userWalletAppointmentRecord -> amount_new = $userWallet['model'] -> appointment;
      $userWalletAppointmentRecord -> setTransaction($transaction);
      if(!$userWalletAppointmentRecord -> create()) {
        $msgs = $userWalletAppointmentRecord['model'] -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }

      $transaction -> commit();
    } catch(\Exception $e) {
      return ['code' => -1, 'msg' => $e -> getMessage()];
    }

    return ['code' => 0, 'msg' => '提现成功', 'user_wallet' => $userWallet['model']];
  }
}
